//
//  MRAlertView.m
//  McRemote
//
//  Created by Yuncheng Shen on 2/18/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MRAlertView.h"

@implementation MRAlertView {
    int _msgCount;
}

@synthesize alertMessageLabel = _alertMessageLabel;
@synthesize alertBackgroundImage = _alertBackgroundImage;

+ (MRAlertView *)sharedAlertView
{
    static MRAlertView *sharedAlertView = nil;
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"MRAlertView" owner:nil options:nil];
        
        for (id object in topLevelObjects) {
            if ([object isKindOfClass:[MRAlertView class]]) {
                sharedAlertView = (MRAlertView *)object;
                
                UIImage *image = [UIImage imageNamed:@"notice_bg.png"]; 
                sharedAlertView.alertBackgroundImage.image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(image.size.height/2, image.size.width/2, image.size.height/2, image.size.width/2)];
            }
        }
    });
    
    return sharedAlertView;
}

- (void)dismiss
{
    [UIView animateWithDuration:0.3 delay:2 options:UIViewAnimationOptionCurveEaseInOut|UIViewAnimationOptionBeginFromCurrentState animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        if (--_msgCount == 0) {
            [self removeFromSuperview];
        }
        
        self.alpha = 1.0;
    }];
}

- (void)showWithTitle:(NSString *)title
{
    self.alertMessageLabel.text = title;
    self.center = CGPointMake(160, 240);
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self];
    
    _msgCount++;
    
    [self dismiss];
}


/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */

@end
